public class NodeServer {

  private MasterService masterService;
  private Node node;

  public NodeServer(MasterService masterService, String nodeId) {
    this.masterService = masterService;
    this.node = new Node(nodeId);
//    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
//      masterService.close();
//    }));
  }

  public void start() {
    try {
      findMaster(node);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private void findMaster(Node node) {
    Node master;
    try {
      master = masterService.electMaster(node, n -> findMaster(n));
      if (master.getId().equals(node.getId())) {
        System.out.println("i am master");
        node.setMaster(true);
      } else {
        System.out.println("i am salve");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void stop() {
    if (node.isMaster()) {
      masterService.close();
    }
  }
}
